package com.example.yiparkapplication.activity.index.activity.myCoupons;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.entity.MonthCard;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.example.yiparkapplication.constant.Constant.LOCALE_CITY_NAME;

public class ReceiverCouponActivity extends BaseActivity implements View.OnClickListener {
    private Handler handler;
    private String mUserId;
    private List<MonthCard> mMonthCardList;
    private String streetName;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_coupon_layout);

        handler = new Handler();
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        mUserId = pref.getString("userId", "");

        if (LOCALE_CITY_NAME == null || "".equals(LOCALE_CITY_NAME)){
            Toast.makeText(getApplicationContext(), "未获取定位，功能无法使用", Toast.LENGTH_LONG).show();
            return;
        }
        getCouponList();
    }

    @Override
    public void onClick(View v){

    }

    private void getCouponList(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_COUPON_LIST + "?parkUserId=" + mUserId + "&cityName=" + LOCALE_CITY_NAME)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code != 100){
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
                JSONArray object = joOut.getJSONArray("object");
                mMonthCardList = new ArrayList<MonthCard>();
                for (int i=0;i<object.size();i++){
                    MonthCard monthCard = new MonthCard();
                    JSONObject cardInfo = object.getJSONObject(i);
                    monthCard.setMonthCardId(cardInfo.getLongValue("monthCardId"));
                    monthCard.setMonthCardName(cardInfo.getString("monthCardName"));
                    monthCard.setStreetName(cardInfo.getString("streetName"));
                    monthCard.setMonthDiscountType(cardInfo.getInteger("monthDiscountType"));
                    monthCard.setMonthDiscountValue(cardInfo.getDouble("monthDiscountValue"));
                    monthCard.setAccessLimit(cardInfo.getDouble("accessLimit"));
                    monthCard.setUsableTimes(cardInfo.getInteger("usableTimes"));
                    monthCard.setStartTime(cardInfo.getString("startTime"));
                    monthCard.setEndTime(cardInfo.getString("endTime"));
                    monthCard.setMonthCardTime(cardInfo.getInteger("monthCardTime"));
                    mMonthCardList.add(monthCard);
                }
                new Thread(){
                    public void run(){
                        handler.post(runnableUi);
                    }
                }.start();
            }
        });
    }

    Runnable runnableUi = new Runnable(){
        @Override
        public void run(){
            RecyclerView vRecyclerView = findViewById(R.id.id_coupon_available_recyclerView);
            vRecyclerView.setLayoutManager(new LinearLayoutManager(ReceiverCouponActivity.this));
            ReceiveCouponAdepter adepter = new ReceiveCouponAdepter(mMonthCardList, ReceiverCouponActivity.this);
        }
    };

    public void appointmentCoupon(String monthCardId){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_APPOINTMENT_COUPON + "?parkUserId=" + mUserId + "&monthCardId=" + monthCardId)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    Looper.prepare();
                    getCouponList();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    public void getDiscountCard(Long monthCardId){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_DISCOUNT_CARD + "?monthCardId=" + monthCardId)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject object = joOut.getJSONObject("object");
                    if (object != null){
                        streetName = object.getString("streetName");
                        ReceiveCouponAdepter.getUsableStreetofReceiveCouponActivity(streetName);
                    }
                }
            }
        });
    }

}
